/*
 * Powered By [rapid-framework]
 * Csdn Code: generate simple CRUD code in single table.
 * Since 2015 - 2017
 */

BUI.use('common/page');
BUI.use(['common/search', 'bui/overlay', 'bui/grid', 'bui/data', 'bui/form'],
    function (Search, Overlay, Grid, Data, Form) {
      var privileges = sessionStorage.getItem('privileges');
      var privilegeList = privileges.split(',');
      var updatePrivilege = false;
      var addPrivilege = false;
      if (privilegeList.length > 0) {
        for (var i = 0; i < privilegeList.length; i++) {
          if (privilegeList[i] == 'updateRecommendCard') {
            updatePrivilege = true;
            continue;
          }
          if (privilegeList[i] == 'saveRecommendCard') {
            addPrivilege = true;
            continue;
          }
        }
      }
      var statusEnum = {
        '1': '有效',
        '2': '作废'
      };
      var typeEnum = {
        '1': '热门卡片',
        '2': '消费热卡',
        '3': '商旅专用',
        '4': '大额定制',
        '5': '女性独享'
      };
      // 查询表单
      var form = new Form.Form({
        srcNode: '#searchForm'
      }).render();
      // 定义表头
      if (updatePrivilege) {
        columns = [
          {
            title: 'id',
            dataIndex: 'cardId',
            visible: false
          },
          {
            title: '银行名称',
            dataIndex: 'bank',
            elCls: 'center',
            width: 180,
            editor: {
              xtype: 'text',
              rules: {
                required: [true, '银行名称不能为空!']
              }
            }
          },
          {
            title: '卡片描述',
            dataIndex: 'cardTitle',
            elCls: 'center',
            width: 200,
            editor: {
              xtype: 'text',
              rules: {
                required: [true, '卡片描述不能为空!']
              }
            }
          },
          {
            title: '卡片详情',
            dataIndex: 'cardContent',
            elCls: 'center',
            width: 180,
            editor: {
              xtype: 'text',
              rules: {
                required: [true, '卡片详情不能为空!']
              }
            }
          },
          {
            title: '卡片封面图片',
            dataIndex: 'cardIcon',
            elCls: 'center',
            width: 180,
            editor: {
              xtype: 'text',
              rules: {
                required: [true, '卡片封面图片不能为空!']
              }
            }
          },
          {
            title: '申请人数',
            dataIndex: 'applyAmount',
            elCls: 'center',
            width: 100,
            editor: {
              xtype: 'text',
              rules: {
                required: [true, '申请人数不能为空!']
              }
            }
          },
          {
            title: '卡片分类',
            render: '.test',
            dataIndex: 'type',
            elCls: 'center',
            width: 120,
            editor: {
              xtype: 'select',
              items: typeEnum,
              rules: {
                required: [true, '卡片分类不能为空!']
              }
            },
            renderer: BUI.Grid.Format
            .enumRenderer(typeEnum)
          },
          {
            title: '卡片状态',
            dataIndex: 'status',
            elCls: 'center',
            width: 100,
            editor: {
              xtype: 'select',
              items: statusEnum,
              rules: {
                required: [true, '卡片状态（1：有效，2:作废)不能为空!']
              }
            },
            renderer: BUI.Grid.Format
            .enumRenderer(statusEnum)
          },
          {
            title: 'APP描述',
            dataIndex: 'pattern',
            elCls: 'center',
            width: 150,
            editor: {
              xtype: 'text',
              rules: {
                required: [true, '申请人数不能为空!']
              }
            }
          },
          {
            title: '操作',
            elCls: 'center',
            width: 100,
            disable: true,
            renderer: function (value, obj) {
              return '<span class="grid-command btn-edit">编辑</span>';
            }
          }];
      } else {
        columns = [
          {
            title: 'id',
            dataIndex: 'cardId',
            visible: false
          },
          {
            title: '银行名称',
            dataIndex: 'bank',
            elCls: 'center',
            width: 180,
            editor: {
              xtype: 'text',
              rules: {
                required: [true, '银行名称不能为空!']
              }
            }
          },
          {
            title: '卡片描述',
            dataIndex: 'cardTitle',
            elCls: 'center',
            width: 200,
            editor: {
              xtype: 'text',
              rules: {
                required: [true, '卡片描述不能为空!']
              }
            }
          },
          {
            title: '卡片详情',
            dataIndex: 'cardContent',
            elCls: 'center',
            width: 200,
            editor: {
              xtype: 'text',
              rules: {
                required: [true, '卡片详情不能为空!']
              }
            }
          },
          {
            title: '卡片封面图片',
            dataIndex: 'cardIcon',
            elCls: 'center',
            width: 200,
            editor: {
              xtype: 'text',
              rules: {
                required: [true, '卡片封面图片不能为空!']
              }
            }
          },
          {
            title: '申请人数',
            dataIndex: 'applyAmount',
            elCls: 'center',
            width: 100,
            editor: {
              xtype: 'text',
              rules: {
                required: [true, '申请人数不能为空!']
              }
            }
          },
          {
            title: '卡片分类',
            render: '.test',
            dataIndex: 'type',
            elCls: 'center',
            width: 120,
            editor: {
              xtype: 'select',
              items: typeEnum,
              rules: {
                required: [true, '卡片分类不能为空!']
              }
            },
            renderer: BUI.Grid.Format
            .enumRenderer(typeEnum)
          },
          {
            title: '卡片状态',
            dataIndex: 'status',
            elCls: 'center',
            width: 100,
            editor: {
              xtype: 'select',
              items: statusEnum,
              rules: {
                required: [true, '卡片状态（1：有效，2:作废)不能为空!']
              }
            },
            renderer: BUI.Grid.Format
            .enumRenderer(statusEnum)
          }];
      }

      // 行编辑
      var editing = new Grid.Plugins.RowEditing({
            triggerCls: 'btn-edit',
            triggerSelected: false

          }),
          // 获取数据
          store = new BUI.Data.Store({
            url: 'listRecommendCard',
            pageSize: 20,
            autoLoad: true,
            remoteSort: true
          });
      // 获取表格对象
      if (addPrivilege) {
        gridCfg = Search.createGridCfg(columns, {
          plugins: [editing, Grid.Plugins.CheckSelection],
          tbar: { // 添加
            items: [{
              btnCls: 'button button-small',
              text: '<i class="icon-plus"></i>添加',
              listeners: {
                'click': addFunction
              }
            }, {
              btnCls: 'button button-small',
              text: '<i class="icon-refresh"></i>刷新',
              listeners: {
                'click': refreshFunction
              }
            }]
          },
        });
      } else {
        gridCfg = Search.createGridCfg(columns, {
          plugins: [editing, Grid.Plugins.CheckSelection],
          tbar: {
            items: [{
              btnCls: 'button button-small',
              text: '<i class="icon-refresh"></i>刷新',
              listeners: {
                'click': refreshFunction
              }
            }]
          }
        });
      }

      // 触发编辑
      editing.on('editorshow', function (ev) {
        var editor = editing.get('curEditor');
        editor.set('errorAlign', {
          points: ['br', 'tr'],
          offset: [0, 10]
        });
      });
      // 编辑提交
      editing.on('accept', function (ev) {
        var record = editing.get('record');
        // console.log(record);
        if (record.hasOwnProperty("b")) {
          delete record["b"];
        }
        if (record.hasOwnProperty("")) {
          delete record[""];
        }
        if (record.hasOwnProperty("createTime")) {
          delete record["createTime"];
        }
        if (record.hasOwnProperty("updateTime")) {
          delete record["updateTime"];
        }
        var saveUrl = record["cardId"] === "" ? 'saveRecommendCard'
            : 'updateRecommendCard';
        jQuery.ajax({
          type: 'POST',
          url: saveUrl,
          dataType: 'json',
          contentType: 'application/json;charset=UTF-8',
          data: JSON.stringify(record),
          complete: function (data) {
            if (data.responseText == "success") { // 删除成功
              search.load();
            } else { // 删除失败
              BUI.Message.Alert('保存失败！');
            }
          }
        });
      });

      // 添加记录
      function addFunction() {
        var newData = {
          b: 0
        };
        store.addAt(newData, 0);
        editing.edit(newData, 'bank'); // 添加记录后，直接编辑
      }

      // 删除选中的记录
      function delFunction() {
        var selections = grid.getSelection();
        delItems(selections);
        store.remove(selections);
      }

      // 刷新
      function refreshFunction() {
        search.load();
      }

      // 查询
      search = new Search({
        store: store,
        autoSearch: true,
        gridCfg: gridCfg
      });
      grid = search.get('grid');
    });